package org.idea.qiyu.threadpool.demo.config;


import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author linhao
 * @Date created in 11:35 上午 2021/10/16
 */
public class SysThreadFactory implements ThreadFactory {

    private AtomicLong taskNumber = new AtomicLong(1);
    private final ThreadGroup group;
    private String threadPrefix;

    public SysThreadFactory(String name) {
        this.threadPrefix = name;
        SecurityManager securityManager = System.getSecurityManager();
        group = ((securityManager != null) ? securityManager.getThreadGroup() : java.lang.Thread.currentThread().getThreadGroup());
    }

    @Override
    public Thread newThread(Runnable r) {
        //设置线程和线程池是属于同一个组的类型
        this.threadPrefix = "sys-" + threadPrefix + "-" + taskNumber.getAndIncrement();
        Thread newThread = new Thread(group,r,threadPrefix,0);
        if(newThread.isDaemon()){
            newThread.setDaemon(false);
        }
        if(newThread.getPriority()!=Thread.NORM_PRIORITY){
            newThread.setPriority(Thread.NORM_PRIORITY);
        }
        return newThread;
    }
}
